package org.phalanx.messenging;

import java.util.ArrayList;

public class PhalanxChatMessage extends AbstractMessage {
	public static final String JOIN_CHAT = "join";
	public static final String PART_CHAT = "part";
	public static final String USER_JOINED = "userjoined";
	public static final String USER_LEFT = "userleft";
	public static final String USER_LIST = "userlist";
	private ArrayList<String> userList; 
	
	public PhalanxChatMessage(){
		super.setMessageHeader("chat");
		userList = new ArrayList<String>();
	}
	
	public void setSender(String sender){
		// This will be filled in by the server
		// so as not to have any sort of spoofing
		// If the client fills this in, it will be ignored
		// and overwritten
		
		super.setToMessage("sender", sender);
	}
	
	public void setAsChatMsg(){
		super.setToMessage("type", "msg");
	}
	
	public void setAsCommand(){
		super.setToMessage("type", "command");
	}
	
	public void setAsStatus(){
		super.setToMessage("type", "status");
	}
	
	public void setStatus(String status){
		super.setToMessage("status", status);
	}
	
	public void setCommand(String command){
		super.setToMessage("command", command);
	}
	
	public void setUserForStatusChange(String username){
		userList.add(username);
		processUserList();
	}
	
	public void removeUserForStatusChange(String username){
		userList.remove(username);
		processUserList();
	}

	private void processUserList(){
		StringBuffer newUserLine = new StringBuffer();

		for (int i = 0; i < userList.size(); i++){
			if (i > 0){
				newUserLine.append(":");
			}
			newUserLine.append(userList.get(i));
		}

		this.setToMessage(USER_LIST, newUserLine.toString());
		
		if (userList.isEmpty()){
			super.messageContents.remove(USER_LIST);
		}
	}
	
	public String getUsersForStatusChange(){
		StringBuffer userString = new StringBuffer();
		userString.append("{");
		for (int i = 0; i < userList.size();i++){
			if (i > 0){
				userString.append(":");
			}
			
			userString.append(userList.get(i));
		}
		
		userString.append("}");
		
		return userString.toString();
	}
	
	public void setChatRoom(String room){
		super.setToMessage("chatroom", room);
	}
	
	public void setMessage(String msg){
		super.setToMessage("msg", msg);
	}
}
